<template>
  <el-form
    ref="userForm"
    :model="userInfo"
    :rules="rules"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="userInfo.password" type="password" style="width:300px" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="hUpdate">更新</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getUserInfoById, saveUserInfoById } from '@/api/user'
export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadUserInfoById()
  },
  methods: {
    hUpdate() {
      this.updateUserInfoById()
    },
    // 加载用户详情
    async loadUserInfoById() {
      try {
        const res = await getUserInfoById(this.$route.params.id)
        // console.log('res', res)
        this.userInfo = res.data.data
        // 保存数据
      } catch (err) {
        console.log('err', err)
      }
    },
    // 更改用户姓名或密码
    async updateUserInfoById() {
      try {
        const res = await saveUserInfoById(this.userInfo)
        console.log('saveUserInfoById', res)
        this.userInfo = res.data.data
        this.$router.back()
        // 保存数据
      } catch (err) {
        console.log('err', err)
      }
    }
  }
}
</script>
